<template>
    <div ref="wrapper">
        <slot></slot>
    </div>
</template>

<script type="text/ecmascript-6">
import BSroll from 'better-scroll'
export default {
    props: {
        // 非实时派发scroll事件
        probeType: {
            type: Number,
            default: 1
        },

        // 是否派发点击事件
        click: {
            type: Boolean,
            default: true
        },

        // 组件数据，用于重新刷新scroll组件
        data: {
            type: Array,
            default: null
        },

        // 是否监听滚动事件
        listenScroll: {
            type: Boolean,
            default: false
        },

        // 是否上拉刷新
        pullup: {
            type: Boolean,
            default: false
        },
        
        beforeScroll: {
            type: Boolean,
            default: false
        },

        // scroll刷新延迟的时间
        refreshDelay: {
            type: Number,
            default: 20
        }
    },
    mounted() {
        setTimeout(() => {
            this._initScroll()
        }, 20)
    },
    methods: {
        _initScroll() {
            if (!this.$refs.wrapper) {
                return
            }
            this.scroll = new BSroll(this.$refs.wrapper, {
                probeType: this.probeType,
                click: this.click
            })

            // 如果传过来的listenscroll为true，则监听
            if (this.listenScroll) {
                let me = this
                this.scroll.on('scroll', (pos) => {
                    me.$emit('scroll', pos)
                })
            }

            // 如果有上拉刷新行为，派发scrollToEnd事件
            if (this.pullup) {
                this.scroll.on('scrollEnd', () => {
                    if (this.scroll.y <= (this.scroll.maxScrollY + 50)) {
                        this.$emit('scrollToEnd')
                    }
                })
            }

            if (this.beforeScroll) {
                this.scroll.on('beforeScrollStart', () => {
                    this.$emit('beforeScroll')
                })
            }
        },
        enable() {
            this.scroll && this.scroll.enable()
        },
        disable() {
            this.scroll && this.scroll.disable()
        },
        refresh() {
            this.scroll && this.scroll.refresh()
        },
        scrollTo() {
            this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
        },
        scrollToElement() {
            this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
        }
    },
    watch: {
        data() {
            setTimeout(() => {
                this.refresh()
            }, this.refreshDelay);
        }
    }
}
</script>

<style lang="stylus" scoped rel="stylesheet/stylus">

</style>